package com.jiawa.train.common.interceptor;

import com.jiawa.train.common.util.MemberContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

//创建一个工具的拦截器进行拦截请求头，获取用户的信息然后将其存储到线程中
@Slf4j
@Component
public class MemberInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            String uri = request.getRequestURI();
            String url = request.getRequestURL().toString();
            log.info("拦截器收到完整的请求路径: " + url);
            System.out.println("拦截器收到请求: " + uri);
            // 手动放行已配置的排除路径
            if (uri.startsWith("/batch/")) {
                return true;
            }
            //获取用户登录信息
            Long memberId = Long.valueOf(request.getHeader("MemberId"));
            log.info("拦截器触发了，header memberId={}", memberId);
            //判断是否获取到用户信息，如果获取到则进行存储
            if(memberId != null){
                MemberContext.setMember(memberId);
            }
            //无论是否获取到用户的信息都要进行放行
            return true;
        }
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            MemberContext.removeMember();
        }
}
